var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cookbookRouter= require('./routes/cookbook')
var searchRouter = require('./routes/search')
var rateRouter = require('./routes/rate')

var app = express();
const cors = require('cors');
app.use(cors({
  origin: '*'
}));
// app.use(cors({
//   origin: ['http://localhost:8080', 'http://127.0.0.1:8080']
// }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(express.static('public'));

app.use('/index', indexRouter);
app.use('/users', usersRouter);
app.use('/cookBook', cookbookRouter);
app.use('/search', searchRouter);
app.use('/rate',rateRouter);


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



let name='';
//配置multer中间件
const multer = require('multer')
obj = multer.diskStorage({
  destination : function(req, file, cb){ //指定目录
    cb(null, 'upload')
  },
  filename : function (req, file, cb){ // 指定文件名
    // console.log(uuid.v1())
    // console.log(uuid.v4())
    name =new Date().getTime() + file.originalname
    // name:  abcd.jpg    xxxdfdd.zip
    // let ext = name.substr(name.lastIndexOf('.'))
    cb(null, name)
  }
})
const uploadTools = multer({
  storage : obj
})
// const uuid = require('uuid')

// 静态资源托管upload目录
app.use(express.static('upload'))

//接收请求
app.post('/upload',
  uploadTools.array('uploadFile'), (req, res)=>{
    console.log(req.files)
    res.send({msg:'OK','name':name})
})







module.exports = app;
